﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Blueprints.Resolution
{
    internal sealed class TypeDiscoverer
    {
        private readonly IReadOnlyList<Type> availableTypes;
        private readonly Dictionary<Type, HashSet<Type>> compatibleTypesByType;

        public TypeDiscoverer(ITypeProvider typeProvider, Type rootType)
        {
            availableTypes = typeProvider.GetAvailableTypes(rootType);
            compatibleTypesByType = new Dictionary<Type, HashSet<Type>>();
            TypeProvider = typeProvider;
        }

        public ITypeProvider TypeProvider
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the compatible types with <paramref name="type"/>. All types provided by the 
        /// TypeProvider, and <paramref name="type"/> are considered.
        /// </summary>
        /// <param name="type">The type to get compatible types for.</param>
        /// <returns>A list of types compatible with <paramref name="type"/>.</returns>
        public IReadOnlyList<Type> GetCompatibleTypes(Type type)
        {
            HashSet<Type> compatibleTypes;
            if (compatibleTypesByType.TryGetValue(type, out compatibleTypes))
            {
                return new List<Type>(compatibleTypes);
            }

            compatibleTypes = new HashSet<Type>();
            Type match;
            if (TryGetMatchingType(type, type, out match))
            {
                compatibleTypes.Add(match);
            }

            foreach (Type candidate in availableTypes)
            {
                if (TryGetMatchingType(type, candidate, out match))
                {
                    compatibleTypes.Add(match);
                }
            }

            compatibleTypesByType[type] = compatibleTypes;
            return new List<Type>(compatibleTypes);
        }

        private bool TryGetMatchingType(Type type, Type candidate, out Type match)
        {
            TypeInfo candidateInfo = candidate.GetTypeInfo();
            if (candidateInfo.IsAbstract || !candidateInfo.IsPublic)
            {
                match = default(Type);
                return false;
            }

            if (candidate == type)
            {
                match = candidate;
                return true;
            }

            if (type.IsArray)
            {
                return TryGetMatchingArrayType(type, candidate, out match);
            }

            TypeInfo typeInfo = type.GetTypeInfo();
            if (typeInfo.IsSealed)
            {
                match = default(Type);
                return false;
            }

            if (!candidateInfo.IsGenericTypeDefinition)
            {
                if (typeInfo.IsAssignableFrom(candidateInfo))
                {
                    match = candidate;
                    return true;
                }
                else
                {
                    match = default(Type);
                    return false;
                }
            }

            if (!typeInfo.IsGenericType || typeInfo.IsGenericTypeDefinition)
            {
                match = default(Type);
                return false;
            }

            Type[] genericArguments = type.GenericTypeArguments;
            if (candidateInfo.GenericTypeParameters.Length != genericArguments.Length)
            {
                match = default(Type);
                return false;
            }

            try
            {
                Type generated = candidate.MakeGenericType(genericArguments);
                if (!typeInfo.IsAssignableFrom(generated.GetTypeInfo()))
                {
                    match = default(Type);
                    return false;
                }

                match = generated;
                return true;
            }
            catch
            {
                match = default(Type);
                return false;
            }
        }

        private bool TryGetMatchingArrayType(Type type, Type candidateElementType, out Type match)
        {
            Type elementType = type.GetElementType();
            if (elementType.IsArray)
            {
                if (!TryGetMatchingArrayType(elementType, candidateElementType, out match))
                {
                    match = default(Type);
                    return false;
                }

                match = match.MakeArrayType();
                return true;
            }

            Type elementMatch;
            if (!TryGetMatchingType(elementType, candidateElementType, out elementMatch))
            {
                match = default(Type);
                return false;
            }

            match = elementMatch.MakeArrayType();
            return true;
        }
    }
}
